import { fs } from 'zx';

const distDir = path.resolve('dist');
const distEditionDir = path.join(distDir, 'editions')
// fs.remove(distDir);

// 启动TW
console.log(chalk.grey.bold('Loading TW core'));
const $tw = require('tiddlywiki/boot/boot').TiddlyWiki();
$tw.boot.argv = ['.'];
$tw.boot.boot();

// 遍历、下载所有发行版
const editionsInfo = [];
const editionCallbackInfo = {
  title: '$:/temp/tw-cpl/edition-callback-info',
  text: {},
  type: 'application/json',
};
const editionInfoTiddlerTitles = $tw.wiki.filterTiddlers('[all[tiddlers]!is[draft]tag[$:/tags/EditionWiki]]');
// 发行版信息列表
const editionInfos = [];
// 已下载的文件记录在这里面，防止重复下载
const downloadFileMap = {};
await fs.mkdirp(distEditionDir); // 发行版目标目录
// DEBUG: console
console.log(`distEditionDir`, distEditionDir);
await $`cp edition_files/* ${distEditionDir}`; // 拷贝本地发行版(未在网络上发布的)
await Promise.all(
  editionInfoTiddlerTitles.map(async (title) => {
    try {
      const tiddler = $tw.wiki.getTiddler(title).fields;
      // DEBUG: console
      console.log(`tiddler`, tiddler);
      // 带有uri，需要下载下来，但是需要是tw支持的格式
      if (
        tiddler['ate.uri'] &&
        tiddler['ate.name'] &&
        (!path.extname(tiddler['ate.uri']) || path.extname(tiddler['ate.uri']) === '.html')
      ) {
        console.log(`- Downloading edition file ${chalk.bold(tiddler['ate.name'])}`);
        const distEditionName = formatTitle(tiddler['ate.name']) + (path.extname(tiddler['ate.uri']) || '.html');
        const htmlContent = await fs.readFile(`${distEditionDir}/${distEditionName}`, 'utf8');
        const tiddlers = $tw.wiki.deserializeTiddlers('text/html', htmlContent)
        const result = tiddlers.filter(item => item.title.startsWith('$:/'))
        // DEBUG: console
        console.log(`result`, result);
        // example see https://talk.tiddlywiki.org/t/choosing-starting-template-a-tw-edition-wiki-template-list-api-json-example/2974/4?u=linonetwo
        const newEditionInfo = {
          // number of non-system, non-plugin tiddlers, too many of these pre-packaged tiddlers may make it difficult to upgrade (can't upgrade via clicking upgrade plugins)
          "tiddlers": tiddlers.length,
          "name": tiddler['ate.name'], // Name
          "locale": [
            // All locales compatible, one of filtering params
            "*-*" // Wildcard that matches all regions and languages
          ],
          "description": "Official release", // Brief descriptions
          "icon": "uri/base64", // Icon, 48x48 recommended, from $:/favicon.ico or img tagged with tag
          "homepage": "https://tiddlywiki.com/", // Homepage or documentation (based on TW)
          "uri": "https://tiddlywiki.com/empty.html", // Url to empty.html
          "lastUpdate": 1234567890, // Unix timestamp, generated by actions (by GitHub or something else) which pull the file from "uri" field; one of filtering params
          "version": "5.1.22", // Version code of core, from actions mentioned above, which tries to boot from the file fetched; one of filtering params
          "size": 3000000, // Size of the file, from the actions mentioned above, one of filtering params
          "valid": true, // Set to false if failed to boot from empty.html and get version codes; clients will ignore templates that are not "valid"
          "author": "Jeremy", // extracted based on non-system tiddler's author,
          "plugins": [
            // extracted using prefix[$:/plugins/] , and get additional info from CPL. This makes sure user get a clue about what it will install
            {
              "title": "$:/plugins/felixhayashi/tiddlymap"
            }
          ],
          "themes": [{ "title": "$:/themes/linonetwo/notion" }]
        }
        editionInfos.push
      }
    } catch (e) {
      console.error(chalk.red.bold(e));
    }
  })
);

/**
 * 格式化 HTML 的名称
 */
function formatTitle(title) {
  return encodeURIComponent(title.replace(/[:/<>"\|?*]/g, '_'));
}
